package com.heima.homeservicemanagementsystem.controller;


import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.json.JSONObject;
import com.heima.homeservicemanagementsystem.config.annotation.RestControllerMapping;
import com.heima.homeservicemanagementsystem.entity.Carouseimage;
import com.heima.homeservicemanagementsystem.entity.ImageVo;
import com.heima.homeservicemanagementsystem.module.Result;
import com.heima.homeservicemanagementsystem.service.CarouseimageService;
import com.heima.homeservicemanagementsystem.utils.DelUtils;
import com.heima.homeservicemanagementsystem.utils.FileUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;

import jakarta.annotation.Resource;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.file.Paths;
import java.sql.Blob;
import java.util.*;

import static com.heima.homeservicemanagementsystem.utils.FileUtils.path;
import static com.heima.homeservicemanagementsystem.utils.FileUtils.targetpath;

/**
 * @Description 文件上传
 * @Author susu
 * @Date 2024/11/25
 */
@Slf4j
@SaIgnore
@Tag(name = "文件上传")
@RestControllerMapping("/common")
public class CommonController {
    //    private final String path = "/uploads/image/";
    @Autowired
    private Environment environment;
    @Resource
    private CarouseimageService carouseimageService;

    @PostMapping("/upload")
    @Operation(summary = "单文件上传")
    public Result<ArrayList<ImageVo>> upload(@RequestParam("file") MultipartFile file) {
        log.info("文件:{}", file);
        String port = environment.getProperty("server.port");
//        System.out.println("Server port: " + port);
        String upload = FileUtils.upload(file);

        ImageVo imageVo = new ImageVo();
        String randomId = UUID.randomUUID().toString();
        imageVo.setUid(randomId);
        imageVo.setName(upload);
        imageVo.setStatus("done");
        imageVo.setUrl("http://127.0.0.1:" + port + "/upload/" + upload);
        ArrayList<ImageVo> objects = new ArrayList<>();
        objects.add(imageVo);

        return Result.success("文件上传成功！", objects);


    }


    /**
     * bolb上传
     *
     * @param file
     * @return com.heima.homeservicemanagementsystem.module.Result<java.util.ArrayList < com.heima.homeservicemanagementsystem.entity.ImageVo>>
     * @author jinchengfei
     * @create 2025/4/2
     **/

    @PostMapping("/uploadBlob")
    public Result<ArrayList<ImageVo>> uploadBlob(@RequestParam("file") MultipartFile file) {
//    public ResponseEntity<ArrayList<ImageVo>> uploadBlob(@RequestParam("file") MultipartFile file) {
        String port = environment.getProperty("server.port");
//        // 检查文件是否为空
        if (file.isEmpty()) {
//            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("文件不能为空");
            return Result.error("文件不能为空");
        }

//        // 打印文件的基本信息进行调试
//        System.out.println("文件名: " + file.getOriginalFilename());
//        System.out.println("文件大小: " + file.getSize());
//        System.out.println("文件类型: " + file.getContentType().split("/")[1]);

        try {
            // 获取文件的字节内容，检查是否能正常读取
            byte[] fileBytes = file.getBytes();
//            System.out.println("文件内容的长度: " + fileBytes.length);

            // 保存文件到指定路径
            String savedFilePath = saveFile(file);
//            System.out.println("文件路径" + savedFilePath);
            ImageVo imageVo = new ImageVo();
            String randomId = UUID.randomUUID().toString();
            imageVo.setUid(randomId);
            imageVo.setName(savedFilePath);
            imageVo.setStatus("done");
            imageVo.setUrl("http://127.0.0.1:" + port + "/upload/" + savedFilePath);
            ArrayList<ImageVo> objects = new ArrayList<>();
            objects.add(imageVo);
            return Result.success("文件上传成功！", objects);
//            return ResponseEntity.ok("文件上传成功，保存路径：" + savedFilePath);
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error("文件上传失败");
//            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("文件上传失败");
        }
    }


    // 处理文件保存逻辑
    private String saveFile(MultipartFile file) throws IOException {
        // 检查文件夹是否存在
        File uploadDir = new File(path);
        File uploadDir2 = new File(targetpath);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();  // 创建文件夹
        }
//        System.out.println("文件类型 "+file);
        // 创建保存的文件路径，使用 UUID 生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        String fileExtension = originalFilename != null ? originalFilename : "";
        System.out.println("suiji" + fileExtension);
        String uniqueFilename = UUID.randomUUID().toString() + fileExtension + "." + file.getContentType().split("/")[1];  // 生成唯一文件名
        System.out.println("文件名字" + uniqueFilename);
        // 创建文件对象并保存
        File savedFile = new File(uploadDir, uniqueFilename);
        file.transferTo(Paths.get(String.valueOf(savedFile)));  // 保存文件
        File savedFile2 = new File(uploadDir2, uniqueFilename);
        file.transferTo(Paths.get(String.valueOf(savedFile2)));  // 保存文件
        log.info("文件地址：{}", String.valueOf(savedFile));
        log.info("文件地址2：{}", String.valueOf(savedFile2));
//        return savedFile.getAbsolutePath();  // 返回文件保存路径
        return uniqueFilename;  // 返回文件保存路径
    }

    private String saveFile2(MultipartFile file) throws IOException {//失败
        // 检查文件夹是否存在
        File uploadDir = new File(path);
        File uploadDir2 = new File(targetpath);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();  // 创建文件夹
        }
        if (!uploadDir2.exists()) {
            uploadDir2.mkdirs();  // 创建文件夹
        }

        // 获取文件的原始名称并生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        String fileExtension = originalFilename != null ? originalFilename : "";
        System.out.println("suiji" + fileExtension);
        String uniqueFilename = UUID.randomUUID().toString() + fileExtension + "." + file.getContentType().split("/")[1]; // 生成唯一文件名
        System.out.println("文件名字" + uniqueFilename);

        // 创建临时文件对象并保存到第一个目录
        File tempFile = new File(uploadDir, uniqueFilename);
        file.transferTo(tempFile);  // 保存文件到第一个目录

        // 创建文件对象并保存到第二个目录
        File tempFile2 = new File(uploadDir2, uniqueFilename);
        file.transferTo(tempFile2);  // 保存文件到第二个目录

        // 删除临时文件
        if (tempFile.exists()) {
            tempFile.delete();  // 删除第一个目录中的文件
        }
        if (tempFile2.exists()) {
            tempFile2.delete();  // 删除第二个目录中的文件
        }

        // 返回文件名
        return uniqueFilename;  // 返回文件保存的唯一名称
    }


    @Transactional(rollbackFor = Exception.class)  // 添加事务管理
    @PostMapping("/del")
    @Operation(summary = "单文件录播图删除")
    public Result<String> DelFile(@RequestBody Carouseimage filename) throws Exception {
        String filename1 = filename.getName();
        log.info("文件:{}", filename);

//        System.out.println("Server port: " + port);
        if (DelUtils.delFile(filename1)) {
            boolean b = carouseimageService.removeBystrId(filename.getUid());
            if (b) {
                return Result.success("文件删除成功！");
            } else {
                throw new Exception("文件删除失败");
            }


        }

        return Result.error("文件删除失败！");

    }


    @PostMapping("/upload/files")
    @Operation(summary = "多文件上传")
    public Result<List<String>> uploadfiles(@RequestParam("file") MultipartFile[] file) {
        String port = environment.getProperty("server.port");
//        System.out.println("Server port: " + port);
        return Result.success("文件上传成功！", FileUtils.uploads(file));


    }


    @SneakyThrows
    @GetMapping("/view/{filename}")
    @Operation(summary = "图片预览")
    public void getImage(@PathVariable String filename, HttpServletResponse response) {
        String contextType = this.getContextType(filename);
        response.setContentType(contextType);
        // 使用ServletOutputStream写入图片数据
        try (ServletOutputStream out = response.getOutputStream();
             BufferedInputStream in = new BufferedInputStream(new FileInputStream(path + filename))) {
            if (contextType.equals("video/mp4")) {
                response.setContentLength(in.available());
            }
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
        }
    }


    // 根据文件名获取文件的 MIME 类型
    private String getContextType(String filename) {
        String sufi = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();
        return switch (sufi) {
            case "PNG", "JPG", "JPEG" -> "image/jpeg"; // 注意这里应该统一为小写的 MIME 类型
            case "GIF" -> "image/gif";
            case "MP4" -> "video/mp4";
            default -> MediaType.APPLICATION_JSON_VALUE; // 默认类型，根据实际情况可能需要调整
        };
    }


}
